#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Function:
	# - Creates a MariaDB database
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#////////////////////////////////////
	# Usage:
	# - /boot/dietpi/func/create_mysql_db <DATABASE_NAME> <DATABASE_USER> <DATABASE_PW>
	#
	# Drop database:
	# - mysqladmin -f drop phpbb3
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Create_MySQL_DB'
	G_CHECK_ROOT_USER
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	# Grab input
	readonly DATABASE_NAME=$1
	readonly DATABASE_USER=$2
	readonly DATABASE_PW=$3
	readonly MESSAGE="Creating MariaDB database $DATABASE_NAME for user $DATABASE_USER"

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////

	# Skip database creation, if already existent
	[[ -d '/var/lib/mysql/'$DATABASE_NAME ]] && { G_DIETPI-NOTIFY 2 "MariaDB database $DATABASE_NAME already exists. Aborting..."; exit 0; }

	# Start MariaDB (No effect if running)
	systemctl start mariadb

	G_DIETPI-NOTIFY 2 "$MESSAGE"

	# Generate DB
	# - 'identified by' can overwrite unix_socket authentication, thus use this for non-root users only.
	grant_privileges="grant all privileges on \`$DATABASE_NAME\`.* to \`$DATABASE_USER\`@localhost identified by '$DATABASE_PW';flush privileges"
	[[ $DATABASE_USER != 'root' ]] || grant_privileges=
	mysql -e "create database \`$DATABASE_NAME\`;$grant_privileges"
	exit_code=$?

	#-----------------------------------------------------------------------------------
	G_DIETPI-NOTIFY -1 $exit_code "$MESSAGE"
	exit $exit_code
	#-----------------------------------------------------------------------------------
}
